#!/bin/sh
echo "[dhcp.script] $*"
[ -z "$1" ] && echo "Error: should be run by udhcpc" && exit 1

BASEDIR=$(dirname $0)
. $BASEDIR/utils.script

set_classless_routes() {
	local max=128
	shift 1

	while [ -n "$1" -a -n "$2" -a $max -gt 0 ]; do
		ip -4 route add "$1" via "$2" dev "$interface"
		max=$(($max-1))
		shift 2
	done
}

setup_interface () {
	hnet-call ifup "{\"ifname\": \"$interface\"}"

	ip -4 route flush dev "$interface"
	ip -4 address flush dev "$interface"

	ifconfig "$interface" "$ip" netmask "${subnet:-255.255.255.0}"

	[ -n "$METRIC" ] && METRIC="metric $METRIC"
	for i in $router; do
		[ "$NODEFAULT" != 1 ] && ip -4 route add default via "$i" dev "$interface" $METRIC
		for r in $CUSTOMROUTES; do
			ip -4 route add "$r" via "$i" dev "$interface" $METRIC
		done
	done

	# CIDR STATIC ROUTES (rfc3442)
	[ -n "$staticroutes" ] && set_classless_routes $staticroutes
	[ -n "$msstaticroutes" ] && set_classless_routes $msstaticroutes

	update_resolv "dhcp" "$interface" "$dns"
	local dnspart=""

	for entry in $dns; do
		if [ -z "$dnspart" ]; then
			dnspart="\"$entry\""
		else
			dnspart="$dnspart, \"$entry\""
		fi
	done

	hnet-call enable_ipv4_uplink "{\"ifname\": \"$interface\", \"dns\": [$dnspart], \"ipv4source\": \"$ip\"}"
}

deconfig_interface() {
	ip -4 route flush dev "$interface"
	ip -4 address flush dev "$interface"
	hnet-call disable_ipv4_uplink "{\"ifname\": \"$interface\"}"
	update_resolv "dhcp" "$interface" ""
}

case "$1" in
	deconfig)
		deconfig_interface
	;;
	renew|bound)
		setup_interface
	;;
esac

# user rules
[ -f /etc/udhcpc.user ] && . /etc/udhcpc.user

exit 0
